package com.leyou.order.task;

import com.leyou.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class CancerOrderOutOfTime {

    @Autowired
    private OrderService orderService;

    final long refreshTime = 5000;//设定5S刷新一次

    @Autowired
    private RedissonClient redissonClient;

    @Scheduled(fixedDelay = refreshTime)//定时扫描清理订单
    public void cancerOrderOutOfTime() {


        // 创建锁对象，并制定锁的名称
        RLock lock = redissonClient.getLock("ly-lock");
        // 获取锁,设置自动失效时间为30s
        boolean isLock = lock.tryLock();
        // 判断是否获取锁
        if (!isLock) {
            // 获取失败
            log.info("【订单服务】取消订单业务，获取锁失败，停止定时任务");
            return;
        }
        try {
            // 执行业务
            log.info("【订单服务】取消订单业务，获取锁成功，执行定时任务");
            // 模拟任务耗时
            //调用order服务的取消订单添加库存业务
            this.orderService.cancerOrder();
        } catch (Exception e) {
            log.error("【订单服务】取消订单业务，任务执行异常", e);
        } finally {
            // 释放锁
            lock.unlock();
            log.info("【订单服务】取消订单业务，任务执行完毕，释放锁");
        }



    }
}
